/**
 * RBAC权限管理API接口
 */

import { request } from '@/utils/request'
import type {
  ApiResponse,
  Role,
  User,
  Permission,
  Resource,
  RoleCreateRequest,
  RoleUpdateRequest,
  RoleListQuery,
  UserCreateRequest,
  UserUpdateRequest,
  UserListQuery,
  PermissionListQuery,
  PermissionAssignRequest,
  UserRoleAssignRequest,
  PermissionCheckRequest,
  ResourceListQuery,
  RoleListResponse,
  RoleDetailResponse,
  UserListResponse,
  UserDetailResponse,
  PermissionListResponse,
  ResourceListResponse,
  PermissionCheckResult,
  UserPermissionInfo
} from '@/types/rbac'

// API路径前缀
const API_PREFIX = '/api/v1/rbac'

/**
 * 角色管理API
 */
export const roleApi = {
  /**
   * 获取角色列表
   */
  async getRoles(params?: RoleListQuery): Promise<RoleListResponse> {
    return request.get(`${API_PREFIX}/roles`, { params })
  },

  /**
   * 获取角色详情
   */
  async getRoleById(id: number): Promise<RoleDetailResponse> {
    return request.get(`${API_PREFIX}/roles/${id}`)
  },

  /**
   * 创建角色
   */
  async createRole(data: RoleCreateRequest): Promise<RoleDetailResponse> {
    return request.post(`${API_PREFIX}/roles`, data)
  },

  /**
   * 更新角色
   */
  async updateRole(id: number, data: RoleUpdateRequest): Promise<RoleDetailResponse> {
    return request.put(`${API_PREFIX}/roles/${id}`, data)
  },

  /**
   * 删除角色
   */
  async deleteRole(id: number): Promise<ApiResponse> {
    return request.delete(`${API_PREFIX}/roles/${id}`)
  },

  /**
   * 获取角色权限
   */
  async getRolePermissions(id: number): Promise<PermissionListResponse> {
    return request.get(`${API_PREFIX}/roles/${id}/permissions`)
  },

  /**
   * 为角色分配权限
   */
  async assignPermissionsToRole(id: number, data: PermissionAssignRequest): Promise<ApiResponse> {
    return request.post(`${API_PREFIX}/roles/${id}/permissions`, data)
  }
}

/**
 * 用户管理API
 */
export const userApi = {
  /**
   * 获取用户列表
   */
  async getUsers(params?: UserListQuery): Promise<UserListResponse> {
    return request.get(`${API_PREFIX}/users`, { params })
  },

  /**
   * 获取用户详情
   */
  async getUserById(id: number): Promise<UserDetailResponse> {
    return request.get(`${API_PREFIX}/users/${id}`)
  },

  /**
   * 创建用户
   */
  async createUser(data: UserCreateRequest): Promise<UserDetailResponse> {
    return request.post(`${API_PREFIX}/users`, data)
  },

  /**
   * 更新用户
   */
  async updateUser(id: number, data: UserUpdateRequest): Promise<UserDetailResponse> {
    return request.put(`${API_PREFIX}/users/${id}`, data)
  },

  /**
   * 删除用户
   */
  async deleteUser(id: number): Promise<ApiResponse> {
    return request.delete(`${API_PREFIX}/users/${id}`)
  },

  /**
   * 获取用户权限
   */
  async getUserPermissions(id: number): Promise<ApiResponse<UserPermissionInfo>> {
    return request.get(`${API_PREFIX}/users/${id}/permissions`)
  },

  /**
   * 为用户分配角色
   */
  async assignRolesToUser(id: number, data: UserRoleAssignRequest): Promise<ApiResponse> {
    return request.post(`${API_PREFIX}/users/${id}/roles`, data)
  },

  /**
   * 重置用户密码
   */
  async resetUserPassword(id: number, newPassword: string): Promise<ApiResponse> {
    return request.post(`${API_PREFIX}/users/${id}/reset-password`, { password: newPassword })
  },

  /**
   * 锁定/解锁用户
   */
  async toggleUserLock(id: number, locked: boolean): Promise<ApiResponse> {
    return request.post(`${API_PREFIX}/users/${id}/toggle-lock`, { locked })
  }
}

/**
 * 权限管理API
 */
export const permissionApi = {
  /**
   * 获取权限列表
   */
  async getPermissions(params?: PermissionListQuery): Promise<PermissionListResponse> {
    return request.get(`${API_PREFIX}/permissions`, { params })
  },

  /**
   * 获取权限详情
   */
  async getPermissionById(id: number): Promise<ApiResponse<Permission>> {
    return request.get(`${API_PREFIX}/permissions/${id}`)
  },

  /**
   * 检查权限
   */
  async checkPermission(data: PermissionCheckRequest): Promise<ApiResponse<PermissionCheckResult>> {
    return request.post(`${API_PREFIX}/permissions/check`, data)
  }
}

/**
 * 资源管理API
 */
export const resourceApi = {
  /**
   * 获取资源列表
   */
  async getResources(params?: ResourceListQuery): Promise<ResourceListResponse> {
    return request.get(`${API_PREFIX}/resources`, { params })
  },

  /**
   * 获取资源详情
   */
  async getResourceById(id: number): Promise<ApiResponse<Resource>> {
    return request.get(`${API_PREFIX}/resources/${id}`)
  },

  /**
   * 创建资源
   */
  async createResource(data: Partial<Resource>): Promise<ApiResponse<Resource>> {
    return request.post(`${API_PREFIX}/resources`, data)
  },

  /**
   * 更新资源
   */
  async updateResource(id: number, data: Partial<Resource>): Promise<ApiResponse<Resource>> {
    return request.put(`${API_PREFIX}/resources/${id}`, data)
  },

  /**
   * 删除资源
   */
  async deleteResource(id: number): Promise<ApiResponse> {
    return request.delete(`${API_PREFIX}/resources/${id}`)
  },

  /**
   * 获取资源树
   */
  async getResourceTree(module?: string): Promise<ApiResponse<Resource[]>> {
    return request.get(`${API_PREFIX}/resources/tree`, { params: { module } })
  }
}

/**
 * 综合RBAC管理API
 */
export const rbacApi = {
  // 继承所有子API
  ...roleApi,
  ...userApi,
  ...permissionApi,
  ...resourceApi,

  /**
   * 获取当前用户权限信息
   */
  async getCurrentUserPermissions(): Promise<ApiResponse<UserPermissionInfo>> {
    return request.get(`${API_PREFIX}/current-user/permissions`)
  },

  /**
   * 获取权限概览统计
   */
  async getPermissionStats(): Promise<ApiResponse<{
    total_users: number
    total_roles: number
    total_permissions: number
    total_resources: number
    active_users: number
    system_roles: number
  }>> {
    return request.get(`${API_PREFIX}/stats`)
  },

  /**
   * 批量分配权限
   */
  async batchAssignPermissions(assignments: Array<{
    role_id: number
    permission_ids: number[]
  }>): Promise<ApiResponse> {
    return request.post(`${API_PREFIX}/permissions/batch-assign`, { assignments })
  },

  /**
   * 批量分配角色
   */
  async batchAssignRoles(assignments: Array<{
    user_id: number
    role_ids: number[]
  }>): Promise<ApiResponse> {
    return request.post(`${API_PREFIX}/roles/batch-assign`, { assignments })
  },

  /**
   * 权限模板管理
   */
  async getPermissionTemplates(): Promise<ApiResponse<Array<{
    id: number
    name: string
    description: string
    permissions: Permission[]
  }>>> {
    return request.get(`${API_PREFIX}/permission-templates`)
  },

  /**
   * 应用权限模板到角色
   */
  async applyPermissionTemplate(roleId: number, templateId: number): Promise<ApiResponse> {
    return request.post(`${API_PREFIX}/roles/${roleId}/apply-template`, { template_id: templateId })
  },

  /**
   * 导出权限配置
   */
  async exportPermissionConfig(format: 'json' | 'csv' | 'excel' = 'json'): Promise<Blob> {
    const response = await request.get(`${API_PREFIX}/export/permissions`, {
      params: { format },
      responseType: 'blob'
    })
    return response as unknown as Blob
  },

  /**
   * 导入权限配置
   */
  async importPermissionConfig(file: File): Promise<ApiResponse> {
    const formData = new FormData()
    formData.append('file', file)
    return request.post(`${API_PREFIX}/import/permissions`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  /**
   * 获取权限变更历史
   */
  async getPermissionHistory(params?: {
    user_id?: number
    role_id?: number
    action?: string
    start_date?: string
    end_date?: string
    page?: number
    size?: number
  }): Promise<ApiResponse<Array<{
    id: number
    action: string
    user_id: number
    role_id?: number
    permission_id?: number
    details: Record<string, any>
    created_at: string
  }>>> {
    return request.get(`${API_PREFIX}/audit/permissions`, { params })
  },

  /**
   * 权限冲突检测
   */
  async detectPermissionConflicts(): Promise<ApiResponse<Array<{
    type: 'duplicate' | 'conflict' | 'orphan'
    description: string
    affected_items: Array<{
      type: 'role' | 'user' | 'permission'
      id: number
      name: string
    }>
    suggestions: string[]
  }>>> {
    return request.get(`${API_PREFIX}/analyze/conflicts`)
  }
}

export default rbacApi